<template>
  <view class="page">
    <!-- 自定义头部 start -->
    <fu-custom bgColor="bg-white" :isBack="false"><block slot="content">{{i18n['授权登录']}}</block></fu-custom>
    <!-- 自定义头部 -->
    <view>
      <view class="header"><image src="/static/logo.png"></image></view>
      <view class="content">
        <view>{{i18n['申请获取以下权限']}}</view>
        <text>{{i18n['获得你的手机号码信息']}}</text>
      </view>
      <button class="bottom bg-green" type="primary" open-type="getPhoneNumber" withCredentials="true" lang="zh_CN" @getphonenumber="getPhoneNumber" style="background:#39b54a;">
       {{ i18n['绑定手机号']}}
      </button>
    </view>
  </view>
</template>

<script>
import { SYSTEM_CONFIG } from '@/common/config.js';
export default {
  data() {
    return {
      code: ''
    };
  },
  methods: {
    // 取消登录
    cancle() {
      uni.navigateBack();
    },
    // 获取手机号
    getPhoneNumber(e) {
      // 用户取消授权,返回上一页
      // 用户同意授权,调用登录方法
      if (e.detail.errMsg.indexOf('user deny') !== -1) {
        uni.navigateBack();
      } else {
        this.bindMoblile(e.detail.encryptedData, e.detail.iv);
      }
    },
    // 绑定手机号
    bindMoblile(encryptedData, iv) {
      uni.showLoading({
        title: this.i18n['绑定中...']
      });
      // 获取用户授权信息
      uni.login({
        success: res => {
          /* 用户信息发给后台 */
          this.$api
            .post(global.apiUrls.postMiniparamMobile, {
              encryptedData: encodeURIComponent(encryptedData),
              iv: encodeURIComponent(iv),
              code: res.code,
              wxinfo: JSON.stringify(uni.getStorageSync('Wxinfo_tmp')),
              user_source: SYSTEM_CONFIG.platform
            })
            .then(res => {
              res = res.data;
              uni.hideLoading();
              if (res.code == 1) {
                uni.removeStorageSync('Wxinfo_tmp');
                // 保存用户信息到 store 中
                this.$store.commit('updateUserInfo', res.data.userinfo);
                uni.navigateBack();
              } else {
                this.$message.info(res.msg);
              }
            })
            .catch(err => {
              uni.hideLoading();
              console.log('ERROR', err);
            });
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #fff;
}

.header {
  height: 400rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  image {
    width: 200rpx;
    height: 200rpx;
  }
}

.content {
  margin-left: 50rpx;
  margin-bottom: 90rpx;
}

.content text {
  display: block;
  color: #9d9d9d;
  margin-top: 40rpx;
}

.bottom {
  border-radius: 80rpx;
  margin: 70rpx 50rpx;
  font-size: 35rpx;
}
</style>
